package com.sduept.nwld.dataserver.controller.dataview;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.faces.view.ViewScoped;
import javax.inject.Named;

import org.apache.commons.lang.StringUtils;
import org.joda.time.DateTime;
import org.primefaces.event.SelectEvent;
import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;
import org.springframework.beans.factory.annotation.Autowired;

import com.sduept.bigdata.fault.manager.WaveFileAssistManager;
import com.sduept.bigdata.web.jsf.controller.AbstractController;
import com.sduept.cim.model.core.Equipment;
import com.sduept.cim.model.core.Substation;
import com.sduept.cim.model.extend.AbstractWaveFile;
import com.sduept.cim.model.extend.LineSegment;
import com.sduept.cim.model.extend.ProtectWaveFile;
import com.sduept.cim.model.extend.WaveFile;
import com.sduept.cim.model.protection.ProtectionEquipment;
import com.sduept.cim.model.protection.WaveEquipment;
import com.sduept.cim.wave.service.WaveEquipmentManager;
import com.sduept.core.dao.SuperDAO;
import com.sduept.core.entity.IdentifiedObject;
import com.sduept.nwld.dataserver.manager.cim.BxCimManager;
import com.sduept.nwld.dataserver.manager.cim.CimManager;
import com.sduept.nwld.dataserver.model.edata.cim.bx.BxSubstation;
import com.sduept.utils.DateUtil;

//@ManagedBean
//@ViewScoped

@Named
@ViewScoped
public class WaveFileInfoController extends AbstractController {

	/**
	 *
	 */
	private static final long serialVersionUID = 751420932679826148L;
	@Autowired
	private SuperDAO dao;
	@Autowired
	private CimManager cm;
	@Autowired
	private WaveEquipmentManager wem;
	@Autowired
	private BxCimManager bcm;
	@Autowired
	private WaveFileAssistManager wfam;

	private List<AbstractWaveFile> waveFileList=new ArrayList<AbstractWaveFile>();
	//查询条件 开始时间
	private Date start;
	//查询条件  结束时间
	private Date end;

	//选择打开某个录波文件，文件id
	private String fileId;
	//当前录波文件的类型
	private Integer type;
	/**
	 * 选择的对象
	 */
	private IdentifiedObject chooseobject;
	/**
	 * 选择对象的名字
	 */
	private String chooseobjectName;
	private StreamedContent file;
	@PostConstruct
	public void init(){
		end = new Date();
		DateTime dt = new DateTime(end);
		start =dt.minusWeeks(1).toDate();
		String startStr = DateUtil.getStringDate(start, DateUtil.pattern_ymdhms);
		String endStr = DateUtil.getStringDate(end, DateUtil.pattern_ymdhms);
		List<WaveFile> wlist  = dao.findByCondition(WaveFile.class, "triggerSecond>=? AND triggerSecond<=?", startStr,endStr);
		List<ProtectWaveFile> plist  = dao.findByCondition(ProtectWaveFile.class, "triggerSecond>=? AND triggerSecond<=?", startStr,endStr);
		waveFileList.addAll(wlist);
		waveFileList.addAll(plist);
		sortWaveFileList();
	}
	/**
	 * 查询
	 */
	public void queryAction(){
		waveFileList.clear();
		List<Object> args = new ArrayList<Object>();
		String startStr = DateUtil.getStringDate(start, DateUtil.pattern_ymdhms);
		String endStr = DateUtil.getStringDate(end, DateUtil.pattern_ymdhms);
		args.add(startStr);
		args.add(endStr);
		String whereSql = "triggerSecond>=? AND triggerSecond<=?";
		if(StringUtils.isNotEmpty(chooseobjectName) && chooseobject!=null){
			if(chooseobject instanceof Equipment){//查询二次设备录波
				whereSql+=" AND equipId=?";
				args.add(chooseobject.getId());
				List<ProtectWaveFile> plist  = dao.findByCondition(whereSql, args.toArray(), "ORDER BY triggerSecond DESC",null,ProtectWaveFile.class);
				waveFileList.addAll(plist);
			}else if(chooseobject instanceof Substation){
				whereSql+=" AND stationName=?";
				args.add(chooseobject.getName());
				List<WaveFile> wlist  = dao.findByCondition(whereSql, args.toArray(), "ORDER BY triggerSecond DESC",null,WaveFile.class);
				List<ProtectWaveFile> plist  = dao.findByCondition(whereSql, args.toArray(), "ORDER BY triggerSecond DESC",null,ProtectWaveFile.class);
				waveFileList.addAll(wlist);
				waveFileList.addAll(plist);
			}else{//查询一次设备录波（包括集中+保护）
				List<WaveEquipment> list=null;
				if(chooseobject instanceof LineSegment)
					list = wem.getLineReferWaveEquipment(chooseobject.getId());
				else
					list = wem.getWaveEquipmentByPrimaryEquipmentId(chooseobject.getId());

				if(list.size()>0){
					String insql = "AND equipId in (";
					for(int i=0;i<list.size();i++){
						if(i==list.size()-1){
							insql+="'"+list.get(i).getId()+"')";
						}else{
							insql+="'"+list.get(i).getId()+"',";
						}
					}
					String firstQuery = whereSql+insql;
					List<WaveFile> wlist  = dao.findByCondition(firstQuery, args.toArray(), "ORDER BY triggerSecond DESC",null,WaveFile.class);
					waveFileList.addAll(wlist);
				}
				List<ProtectionEquipment> mainList = cm.listMainEquipmentsByprotectedId(chooseobject.getId());
				if(mainList.size()>0){
					String insql = "AND equipId in (";
					for(int i=0;i<mainList.size();i++){
						if(i==mainList.size()-1){
							insql+="'"+mainList.get(i).getId()+"')";
						}else{
							insql+="'"+mainList.get(i).getId()+"',";
						}
					}
					String secondQuery = whereSql+insql;
					List<ProtectWaveFile> plist  = dao.findByCondition(secondQuery, args.toArray(), "ORDER BY triggerSecond DESC",null,ProtectWaveFile.class);
					waveFileList.addAll(plist);
				}
			}
		}else{
			List<WaveFile> wlist  = dao.findByCondition(whereSql, args.toArray(), "ORDER BY triggerSecond DESC",null,WaveFile.class);
			List<ProtectWaveFile> plist  = dao.findByCondition(whereSql, args.toArray(), "ORDER BY triggerSecond DESC",null,ProtectWaveFile.class);
			waveFileList.addAll(wlist);
			waveFileList.addAll(plist);
		}
		sortWaveFileList();
	}
	private void sortWaveFileList(){
		for(AbstractWaveFile wf:waveFileList){
			if(StringUtils.isEmpty(wf.getStationName())){
				String[] str = wf.getPath().split("/");
				if(str.length>0){
					BxSubstation bxs = bcm.getBxSubstationById(str[0]);
					if(bxs!=null)
						wf.setStationName(bxs.getMname());
				}
			}
		}
		Collections.sort(waveFileList,new Comparator<AbstractWaveFile>() {
			@Override
			public int compare(AbstractWaveFile arg0, AbstractWaveFile arg1) {
				long t1 = DateUtil.getDateByString(arg0.getTriggerSecond(), DateUtil.pattern_ymdhms).getTime();
				long t2 = DateUtil.getDateByString(arg1.getTriggerSecond(), DateUtil.pattern_ymdhms).getTime();
				return t1>t2?-1:t1<t2?1:0;
			}
		});
	}
	/**
	 * 点击录波连接
	 * @param wf
	 */
	public void prepareOpenWaveView(AbstractWaveFile wf){
		fileId = wf.getId();
		if(wf instanceof WaveFile)
			type=1;
		else
			type = 2;
	}

	public void openSelectEquipmentDialog(){
		Map<String, Object> options = new HashMap<String, Object>();
		options.put("resizable", true);
		options.put("draggable", true);
		options.put("modal", false);
		options.put("width", 600);
		options.put("height", 400);
		openDialog("/ui/common/equipment_selector_single",null, options);
	}
	public void prepareDownload(AbstractWaveFile wf){
		FileInputStream fis = null;
		try {
			fis = wfam.generateDownloadZipFile(wf);
			file = new DefaultStreamedContent(fis, "application/octet-stream", wf.getEquipment() + ".zip") ;
		} catch (FileNotFoundException e1) {
			e1.printStackTrace();
		}
		if(file == null) {
			addErrorMessage("查找文件失败，无法下载");
		}
	}
	public void onObjectSelectorChosen(SelectEvent event) {
		chooseobject = (IdentifiedObject) event.getObject();
		chooseobjectName = chooseobject.getName();
	}
	public void clearObjectSelectorChosen() {
		chooseobject = null;
		chooseobjectName = null;
		queryAction();
	}
	public List<AbstractWaveFile> getWaveFileList() {
		return waveFileList;
	}
	public Date getStart() {
		return start;
	}
	public Date getEnd() {
		return end;
	}
	public void setStart(Date start) {
		this.start = start;
	}
	public void setEnd(Date end) {
		this.end = end;
	}
	public String getFileId() {
		return fileId;
	}
	public void setFileId(String fileId) {
		this.fileId = fileId;
	}
	public IdentifiedObject getChooseobject() {
		return chooseobject;
	}
	public void setChooseobject(IdentifiedObject chooseobject) {
		this.chooseobject = chooseobject;
	}
	public String getChooseobjectName() {
		return chooseobjectName;
	}
	public void setChooseobjectName(String chooseobjectName) {
		this.chooseobjectName = chooseobjectName;
	}
	public Integer getType() {
		return type;
	}
	public void setType(Integer type) {
		this.type = type;
	}
	public StreamedContent getFile() {
		return file;
	}
	public void setFile(StreamedContent file) {
		this.file = file;
	}


}
